package cn.kgc.advice;

import cn.hutool.core.date.StopWatch;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import static cn.kgc.base.SystemConstant.TOTAL_TIME;

/**
 * @author wangyue
 * @version 1.0
 * 记录接口执行时间
 */
@Aspect
@Component
@Slf4j
@SuppressWarnings("all")
public class TimingAdvice {
    @Pointcut("execution(* cn.kgc.controller.*.*(..))")
    public void pointcut1(){}

    @Around("pointcut1()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        StopWatch stopWatch=new StopWatch();
        stopWatch.start();
        Object target = joinPoint.proceed(); //执行目标方法
        stopWatch.stop();
        double totalTimeSeconds = stopWatch.getTotalTimeSeconds();    //获得目标方法的执行时间
        if(totalTimeSeconds>TOTAL_TIME){
            String className = joinPoint.getTarget().getClass().getName();  //目标类名
            String methodName = joinPoint.getSignature().getName();  //目标方法名
            log.warn(className+":"+methodName+"执行时间超过2秒,耗时："+totalTimeSeconds+"秒");
        }
        return target;
    }
}
